//
//  RigthViewController.m
//  YiXiu
//
//  Created by tianshikechuang on 16/7/1.
//  Copyright © 2016年 zzz. All rights reserved.
//

#import "RigthViewController.h"

#import "BaseCollectionViewCell.h"
#import "CollectionSectionHeadV.h"

#define lineSpace  20
#define interSpace 20

#define collectWidth [UIScreen mainScreen].bounds.size.width - 20
#define itemWidth  (collectWidth - interSpace * 3)/4.0
#define itemheigth 40

@interface RigthViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, copy) NSMutableArray * firstCellArr;
@property (nonatomic, copy) NSMutableArray * secondCellArr;
@property(nonatomic, strong) NSArray * dataSource;
//@property(nonatomic, strong) BaseTableViewCell * firstCell;
//@property(nonatomic, strong) BaseTableViewCell * secondCell;

@property(nonatomic, strong) UIButton * editButton;
@property(nonatomic, strong)  CAKeyframeAnimation *keyAnimation;

@end

@implementation RigthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
    view.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:view];
    
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth -60, 20, 60, 40)];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview: button];
    
    [self.view addSubview:self.collectionView];
}


-(void)buttonAction:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}




- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * fl = [[UICollectionViewFlowLayout alloc] init];
        fl.itemSize = CGSizeMake(itemWidth, itemheigth);
        fl.minimumLineSpacing = 20;
        fl.minimumInteritemSpacing = 20;
        fl.headerReferenceSize = CGSizeMake(300, 50);
        
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height - 64) collectionViewLayout:fl];
        [_collectionView registerNib:[UINib nibWithNibName:@"BaseCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
        [_collectionView registerClass:[CollectionSectionHeadV class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView"];
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
        [_collectionView addGestureRecognizer:longGesture];
        
    }
    return _collectionView;
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataSource.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return  ((NSArray *)self.dataSource[section]).count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    BaseCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.editButton.selected) {
        [cell.layer removeAllAnimations];
        [cell.layer addAnimation:self.keyAnimation forKey:nil];
    }
    ((BaseCollectionViewCell *)cell).titleLabel.text = self.dataSource[indexPath.section][indexPath.row];
    
}


// 设置每组的头部视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableview = nil;
    if (kind == UICollectionElementKindSectionHeader){
        
        CollectionSectionHeadV *headerV = (CollectionSectionHeadV *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView" forIndexPath:indexPath];
        [headerV setTextTitle];
        reusableview = headerV;
    }
    
    if (indexPath.section == 0) {
        [reusableview addSubview:self.editButton];
    }
    
    
    return reusableview;
    
}




// 点击cell的时候，有上下切换
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.editButton.selected) {
        
        id obj = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.item];
        [[self.dataSource objectAtIndex:indexPath.section] removeObject:obj];
        if (indexPath.section == 0) {
            [[self.dataSource objectAtIndex:1] insertObject:obj atIndex:0];
            
        }else{
            [[self.dataSource objectAtIndex:0] addObject:obj];
            
        }
        
        [collectionView reloadData];
    }
    
}



// 长按 拖动手势
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
    //判断手势状态
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{
            //判断手势落点位置是否在路径上
            NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:[longGesture locationInView:self.collectionView]];
            if (indexPath == nil) {
                break;
            }
            //在路径上则开始移动该路径上的cell
            [self.collectionView beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:
            //移动过程当中随时更新cell位置
            [self.collectionView updateInteractiveMovementTargetPosition:[longGesture locationInView:self.collectionView]];
            break;
        case UIGestureRecognizerStateEnded:
            //移动结束后关闭cell移动
            [self.collectionView endInteractiveMovement];
            break;
        default:
            [self.collectionView cancelInteractiveMovement];
            break;
    }
}


- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    //返回YES允许其item移动
    return YES;
}
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    //取出源item数据
    id objc = [self.dataSource objectAtIndex:sourceIndexPath.section][sourceIndexPath.item];
    //从资源数组中移除该数据
    [[self.dataSource objectAtIndex:sourceIndexPath.section] removeObject:objc];
   
    //将数据插入到资源数组中的目标位置上
    [[self.dataSource objectAtIndex:destinationIndexPath.section] insertObject:objc atIndex:destinationIndexPath.item];
    
}




- (void)beginShake{
    for (UIView * view in self.collectionView.subviews) {
        if ([view isKindOfClass:[BaseCollectionViewCell class]]) {
            [view.layer removeAllAnimations];
            [view.layer addAnimation:self.keyAnimation forKey:nil];
        }
    }
}

- (void)endShake{
    for (UIView * view in self.collectionView.subviews) {
        if ([view isKindOfClass:[BaseCollectionViewCell class]]) {
            [view.layer removeAllAnimations];
        }
    }
}



-(void)ViewRightAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self beginShake];
    }else{
        [self endShake];
    }
    
}



- (UIButton *)editButton{
    if (!_editButton) {
        UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(KScreenWidth - 100, 2, 80, 40)];
        button.backgroundColor = HWColor(110, 205, 255);
        [button setTitle:@"编辑" forState:UIControlStateNormal];
        [button setTitle:@"完成" forState:UIControlStateSelected];
        [button addTarget:self action:@selector(ViewRightAction:) forControlEvents:UIControlEventTouchUpInside];
        _editButton = button;
    }
    return _editButton;
}



- (CAKeyframeAnimation *)keyAnimation{
    if (!_keyAnimation) {
        CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
        
        keyAnimation.values = @[@(-M_1_PI/4), @(M_1_PI/4), @(-M_1_PI/4)];
        
        keyAnimation.repeatCount = CGFLOAT_MAX;
        
        keyAnimation.duration = 0.12;     //all animation's duration is 0.25
        _keyAnimation = keyAnimation;
    }
    return _keyAnimation;
}



- (NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = @[self.firstCellArr,self.secondCellArr];
    }
    return _dataSource;
}

- (NSMutableArray *)firstCellArr{
    if (!_firstCellArr) {
        _firstCellArr = [NSMutableArray array];
        for (int i = 0; i < 20; i++) {
            
            [_firstCellArr addObject:[NSString stringWithFormat:@"%.2f",i + 1.0]];
        }
    }
    return _firstCellArr;
}

- (NSMutableArray *)secondCellArr{
    if (!_secondCellArr) {
        _secondCellArr = [NSMutableArray array];
        for (int i = 20; i < 50; i++) {
            
            [_secondCellArr addObject:[NSString stringWithFormat:@"%.2f",i +1.0]];
        }
    }
    return _secondCellArr;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
